from sqlalchemy.orm import Session
from models import Task
import time
import uuid


def create_task(db: Session, question: str, file_path: str = None):
    task_id = str(uuid.uuid4())
    timestamp = int(time.time())
    
    db_task = Task(
        id=task_id,
        status="processing",
        question=question,
        file_path=file_path,
        created_at=timestamp,
        updated_at=timestamp
    )
    db.add(db_task)
    db.commit()
    db.refresh(db_task)
    return {"task_id": task_id, "status": "processing"}

def get_task_status(db: Session, task_id: str):
    db_task = db.query(Task).filter(Task.id == task_id).first()
    if db_task:
        return {
            "task_id": db_task.id,
            "status": db_task.status,
            "question": db_task.question,
            "file_path": db_task.file_path,
            "result": db_task.result,
            "created_at": db_task.created_at,
            "updated_at": db_task.updated_at
        }
    return {"error": "Task not found"}

def get_all_tasks(db: Session):
    tasks = db.query(Task).order_by(Task.created_at.desc()).all()
    return [
        {
            "task_id": task.id,
            "status": task.status,
            "question": task.question,
            "file_path": task.file_path,
            "result": task.result,
            "created_at": task.created_at,
            "updated_at": task.updated_at
        }
        for task in tasks
    ]

def update_task_status(db: Session, task_id: str, status: str, result: str = None):
    try:
        # 尝试查找指定任务
        db_task = db.query(Task).filter(Task.id == task_id).first()
        if db_task is None:
            # 若任务不存在，返回错误信息
            return {"error": "Task not found"}
        
        # 更新任务状态、结果和更新时间
        db_task.status = status
        db_task.result = result
        db_task.updated_at = int(time.time())
        
        # 提交更改到数据库
        db.commit()
        # 刷新任务对象以获取最新状态
        db.refresh(db_task)
        
        return {"message": "Task status updated successfully", "task_id": task_id}
    except Exception as e:
        # 若发生异常，回滚更改并返回错误信息
        db.rollback()
        return {"error": f"An error occurred while updating task status: {str(e)}"}
